/* eslint-disable default-case */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  accufundList,
  accufundOsList,
  accufundSendInfor,
  accufundAdd,
  accufundDetail,
  accufundUpdateDetail,
  accufundUpdate,
  accufundToDeal,
  accufundToDealComplete,
  accufundCancelToDeal,
  accufundaddHdlRemark,
  accufundHdlRemark,
  accufundAddCheck,
  accufundsubmitToRun,
  accufundToDealDetial,
  addRefundInfor,
  addContactInfor,
  accuGrants,
  signPro,
  getProList,
  insertProbFdbk,
  getProBaseList,
  cancelProbFlag,
  getEmpNameList,
  originCircle,
  checkAccuInfor,
  getRefundInfor,
  uploadFileBatch,
  uploadFileModify,
  uploadFileGrant,
} from '@/services/accufundservice';
import { getUploadProgress } from '@/services/careermange';
import { getMatList } from '@/services/socialservice';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'accuservicehandle';

export default {
  namespace,
  state: {
    formFieldsValue: {},
    flag: false,
    expandForm: false,
    activeKey: '1',
    issWayArr: [{ itemCode: '1', itemName: '现场发放' }, { itemCode: '2', itemName: '快递邮寄' }],
    tabList: [
      { itemCode: '1', itemName: '待办理' },
      { itemCode: '2', itemName: '办理中' },
      { itemCode: '3', itemName: '已办理' },
      { itemCode: '5', itemName: '问题人员' },
      { itemCode: '4', itemName: '已取消' },
    ],
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    sendData: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
    },
    detail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      accuSerHdl: {},
      originalRemark: {},
      accuRefundInfo: [],
      matlist: [],
      remarklist: [],
    },
    updatedetail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insCardHdl: {},
      elementArr: {},
      matFileDictItem: {},
    },
    detailHdl: [],
    contactList: [],
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    },
    proBaseList: {},
    proFbList: [],
    proVno: 0,
    toDealList: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insSerHdl: {},
      matlist: [],
      originalRemark: {},
      selectedRows: [],
      remmarkList: [],
      insRefundInfo: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 10,
        },
      },
    },
    empNameSelect: [],
    empNameList: [],
    elementArr: [],
    matFileDictItem: [],
    messageData: {},
    refundObj: {},
    batchQuery: {
      // 批量上传数据
      areaId: null,
      contType: null,
      progressPercent: 0,
    },
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/esApi/accuSerHdl/accuBatchIssueErrData', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
  },

  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(accufundList, payload); // 请求
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 运行列表
    *fetchOsList({ payload }, { call, put }) {
      const response = yield call(accufundOsList, payload); // 请求
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 获取派单信息
    *fetchSendInfor({ payload }, { call, put }) {
      const response = yield call(accufundSendInfor, payload);
      if (response.success) {
        yield put({
          type: 'sendList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 添加数据
    addList:[
      function* ({ payload, callback }, { call }) {
      const response = yield call(accufundAdd, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    { type:'throttle', ms:10000}
  ],
    // 获取详情
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(accufundDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 修改页详情
    *fetchUpdateDetail({ payload }, { call, put }) {
      const response = yield call(accufundUpdateDetail, payload);
      if (response.success) {
        yield put({
          type: 'getUpdateDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
        yield put(routerRedux.goBack());
      }
    },
    // 修改
    updateList:[
      function*({ payload, callback }, { call }) {
      const response = yield call(accufundUpdate, payload);
      if (response.success) {
        callback(response.success);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    { type:'throttle',ms:10000 }
  ],
    // 开始办理-查看
    *updateToDealDetial({ payload }, { call, put }) {
      const response = yield call(accufundToDealDetial, payload);
      if (response.success) {
        yield put({
          type: 'getToDealDetial',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 开始办理
    *updateToDeal({ payload, callback }, { call }) {
      const response = yield call(accufundToDeal, payload);
      if (response.success) {
        callback(response.success);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 办理完成
    *updateToDealComplete({ payload, callback }, { call }) {
      const response = yield call(accufundToDealComplete, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 取消办理
    *cancelToDeal({ payload, callback }, { call }) {
      const response = yield call(accufundCancelToDeal, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 提交运行
    *submitToRun({ payload, callback }, { call }) {
      const response = yield call(accufundsubmitToRun, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 发放
    *updateGrants({ payload, callback }, { call }) {
      const response = yield call(accuGrants, payload);
      callback(response);
    },
    // 服务办理--办理备注
    *detailHdlRemark({ payload }, { call, put }) {
      const response = yield call(accufundHdlRemark, payload);
      if (response.success) {
        yield put({
          type: 'getHdlRemark',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 办理备注
    *addHdlRemark({ payload, callback }, { call }) {
      const response = yield call(accufundaddHdlRemark, payload);
      if (callback) callback(response);
    },
    // 办理备注历史
    *addHdlRemarkDel({ payload, callback }, { call, put }) {
      const response = yield call(accufundaddHdlRemark, payload);
      if (response.success) {
        callback(response);
        const resAgin = yield call(accufundHdlRemark, { busiId: payload.busiId });
        if (resAgin.success) {
          yield put({
            type: 'updateData',
            payload: resAgin.data,
          });
        } else {
          message.warning(response.message || '服务端错误');
        }
      }
    },
    // 校验
    *addCheckList({ payload, callback }, { call }) {
      const response = yield call(accufundAddCheck, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message);
      }
    },
    // 获取返款信息
    *getRefund({ payload }, { call, put }) {
      const response = yield call(getRefundInfor, payload);
      if (response.success) {
        yield put({
          type: 'getRefundInfor',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 新增返款
    *addRefund({ payload, callback }, { call }) {
      const response = yield call(addRefundInfor, payload);
      callback(response);
    },
    // 联系
    *addContact({ payload }, { call, put }) {
      const response = yield call(addContactInfor, payload);
      if (response.success) {
        yield put({
          type: 'getContact',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 标记问题人员
    *signPro({ payload, callback }, { call }) {
      const response = yield call(signPro, payload);
      if (callback) {
        callback(response);
      }
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getProList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 获取问题人员详情
    *fetchProBaseList({ payload }, { call, put }) {
      const response = yield call(getProBaseList, payload);
      if (response.success) {
        yield put({
          type: 'getProBaseList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 社保服务办理问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(insertProbFdbk, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 反馈并取消
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(cancelProbFlag, payload);
      if (callback) {
        callback(response);
      }
    },
    *fetchMatList({ payload }, { call, put }) {
      const response = yield call(getMatList, payload);
      if (response.success) {
        yield put({
          type: 'getMatList',
          payload: response.data,
        });
        return response;
      }
      return message.warning(response.message || '服务端错误');
    },
    // 获取模糊查询员工姓名列表
    *fetchEmpNameList({ payload }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'getEmpNameList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
        }
        if (!response.data.length) {
          message.warning('当前所输的不存在，请检查 ');
        }
      } else {
        message.warning(response.message);
      }
    },
    *fetchEmpNoList({ payload, callback }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data.length) {
          yield put({
            type: 'getEmpNoList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
          callback(false);
        } else {
          callback(true);
          message.warning('当前所输的证件号不存在，请检查 ');
        }
      } else {
        callback(true);
        message.warning(response.message);
      }
    },
    // 原件流转
    *circle({ payload, callback }, { call }) {
      const response = yield call(originCircle, payload);
      if (callback) callback(response);
    },
    // 新增校验
    *checkAccu({ payload, callback }, { call, put }) {
      const response = yield call(checkAccuInfor, payload);
      if (response.rspCode === '101') {
        callback(true);
        yield put({
          type: 'messageData',
          payload: response.message,
        });
      } else {
        callback(false);
      }
    },
    // 获取进度
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function*({ payload }, { call, put }) {
      try {
        let api;
        if (payload.type === 'batch') {
          api = uploadFileBatch;
        }
        if (payload.type === 'modify') {
          api = uploadFileModify;
        }
        if (payload.type === 'grant') {
          api = uploadFileGrant;
        }
        const response = yield call(api, payload.formData);
        if (response.success) {
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type:'throttle', ms:10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.accuservicehandle);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // *handleBatchTask({ payload }, { put, select }) {
    //   const state = yield select(s => s.accuservicehandle);
    //   let { showProgress, resultInfo, currentStep } = state;
    //   showProgress = true;
    //   if (payload.successProp >= 100) {
    //     resultInfo.errorParams = {
    //       batNo: payload.batchId,
    //     };
    //     resultInfo = { ...resultInfo, ...payload };
    //     currentStep += 1;
    //     showProgress = false;
    //     // 先更新进度
    //     yield put({
    //       type: 'updateBatchTask',
    //       payload: {
    //         progressPercent: payload.successProp,
    //         resultInfo,
    //       },
    //     });
    //     yield delay(3000);
    //     // 再更新状态
    //     yield put({
    //       type: 'updateBatchTask',
    //       payload: {
    //         currentStep,
    //         showProgress,
    //       },
    //     });
    //   } else {
    //     yield put({
    //       type: 'updateBatchTask',
    //       payload: { progressPercent: payload.successProp, resultInfo },
    //     });
    //   }
    // },
  },

  reducers: {
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新数据
    updateData(state, { payload }) {
      const remarklist = payload;
      return {
        ...state,
        detail: { ...state.detail, remarklist },
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 展示消息
    messageData(state, { payload }) {
      return {
        ...state,
        messageData: payload,
      };
    },
    // 派单信息
    sendList(state, { payload }) {
      return {
        ...state,
        sendData: payload,
      };
    },
    // 获取详情
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    // 修改页面详情
    getUpdateDetail(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.serMatPkgVo.maGpages ? payload.serMatPkgVo.maGpages : [];
      if (maGpages.length) {
        maGpages.map(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.map(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
                obj.children.map(c => {
                  const newC = c;
                  if (Number(c.inpType) === 11) {
                    newC.areaValue = c.inpVal ? c.inpVal.split(',') : undefined;
                    newC.name = d.inpValName;
                  }
                  return true;
                });
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                    status: 'done',
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.matId = d.matId;
              obj.inpType = d.inpType;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              if (d.inpVal) {
                obj.inpVal = d.inpVal;
              } else {
                obj.inpVal = d.dftVal;
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              elementArr.push(obj);
              return true;
            });
          }
          return true;
        });
      }
      const { matFileDictItem } = payload.serMatPkgVo;
      const { empBaseInfoVo } = payload;
      const { empSendInfoVo } = payload;
      const insCardHdl = payload.accuSerHdl;
      Object.keys(insCardHdl).forEach(key => {
        if (key === 'copyFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        } else if (key === 'masterFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        }
      });
      return {
        ...state,
        coltFlag: payload.serMatPkgVo.coltFlag,
        updatedetail: { elementArr, matFileDictItem, empBaseInfoVo, empSendInfoVo, insCardHdl },
      };
    },

    // 办理备注
    getHdlRemark(state, { payload }) {
      return {
        ...state,
        detailHdl: Array.isArray(payload) ? payload : [],
      };
    },
    // 联系记录
    getContact(state, { payload }) {
      return {
        ...state,
        contactList: Array.isArray(payload) ? payload : [],
      };
    },
    // 问题列表
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proListData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 获取返款信息
    getRefundInfor(state, { payload }) {
      return {
        ...state,
        refundObj: payload.data,
      };
    },
    // 开始办理
    getToDealDetial(state, { payload }) {
      const {
        empSendInfoVo,
        empBaseInfoVo,
        accuSerHdl,
        matlist,
        origInalRemark,
        insRefundInfo,
        selectedRows,
        remmarkList,
      } = payload.data;
      return {
        ...state,
        toDealList: {
          empSendInfoVo,
          empBaseInfoVo,
          insSerHdl: { ...accuSerHdl },
          matlist,
          origInalRemark,
          insRefundInfo,
          selectedRows,
          remmarkList,
        },
      };
    },
    // 问题人员详情
    getProBaseList(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbks,
      };
    },
    // 修改返款
    refunds(state, { payload }) {
      return {
        ...state,
        updatedetail: {
          ...state.updatedetail,
          insCardHdl: { ...state.updatedetail.insCardHdl, ...payload },
        },
      };
    },
    // 获取材料
    getMatList(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.maGpages ? payload.maGpages : [];
      if (maGpages.length) {
        maGpages.map(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.map(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
              }
              obj.dftVal = d.dftVal; // 默认值
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.matId = d.matId;
              obj.inpType = d.inpType;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              obj.inpVal = d.inpVal; // 默认值
              elementArr.push(obj);
              return true;
            });
          }
          return true;
        });
      }
      const { matFileDictItem } = payload;
      elementArr.map((element, i) => {
        if (element.children && element.children.length) {
          element.children.map(item => {
            if (+item.judgeLogicCode === +element.dftVal) {
              elementArr.splice(i + 1, 0, item);
            }
            return true;
          });
        }
        return true;
      });
      return {
        ...state,
        ...payload,
        elementArr,
        matFileDictItem,
      };
    },
    // 材料信息详细
    matInfor(state, { payload }) {
      const { element } = payload;
      let { elementArr } = payload;
      if (String(element.inpType) === '4') {
        let index;
        elementArr.map((elem, i) => {
          if (+elem.pageDetailId === +element.pageDetailId) {
            index = i;
          }
          return true;
        });
        if (element.children && element.children.length) {
          element.children.map(item => {
            if (+item.judgeLogicCode === +element.inpVal) {
              elementArr.splice(index + 1, 0, item);
            } else {
              elementArr = elementArr.filter(ele => ele.matId !== item.matId);
            }
            return true;
          });
        }
      }
      return {
        ...state,
        elementArr,
      };
    },
    // 展示人员
    getEmpNameList(state, { payload }) {
      const empData = Array.isArray(payload) ? payload : [];
      return {
        ...state,
        empNameList: empData,
        empNameSelect: empData,
      };
    },
    // 选择人员信息
    fetchEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 选择身份证信息
    getEmpNoList(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 清空
    clearEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 更新state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新页码数据
    updateModelPage(state, { payload }) {
      const { current, pageSize } = payload;
      return {
        ...state,
        pageData: {
          list: [],
          pagination: { current, pageSize },
        },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
